NodeMCU
Pin Configuration of NodeMCU
#include <ESP8266WiFi.h> #include <PubSubClient.h> const char* ssid = "WIFI-NAME"; const char* password = "WIFI-PASSWORD"; const char* mqtt_server = "test.mosquitto.org"; const char* device_id = "esp8266"; WiFiClient espClient; PubSubClient client(espClient); //====================================== // CALLBACK FUNCTION //======================================= void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived [");Serial.print(topic);Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); if ((char)payload[0] == '1') { digitalWrite(D1, HIGH); } else{ digitalWrite(D1, LOW); // Turn the LED off by making the voltage HIGH } } //====================================== // RECONNECT FUNCTION //======================================= void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection..."); if (client.connect(device_id)) { Serial.println("connected"); client.subscribe("esp8266/light/gemlabs"); } } } //====================================== // SETUP FUNCTION //======================================= void setup() { Serial.begin(9600); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected");Serial.println("IP address: ");Serial.println(WiFi.localIP()); pinMode(D1, OUTPUT); client.setServer(mqtt_server, 1883); client.setCallback(callback); } //====================================== // LOOP FUNCTION //======================================= void loop() { if (!client.connected()) { reconnect(); } client.loop(); }